package com.dragon.connector.imServer.serverProcesser;

import com.dragon.connector.imServer.protoBuilder.ReceiveMessageResponseBuilder;
import com.dragon.connector.imServer.session.LocalSession;
import com.dragon.connector.imServer.session.ServerSession;
import com.dragon.connector.imServer.session.service.SessionManger;
import com.dragon.protoJo.ProtoInstant;
import com.dragon.protoJo.bean.msg.ProtoMsg;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class ReceiveMessageProcesser extends AbstractServerProcesser{

    @Override
    public ProtoMsg.HeadType op() {
        return ProtoMsg.HeadType.MESSAGE_REQUEST;
    }

    /**
     * 接收websocket消息
     * @param session
     * @param proto
     * @return
     */
    @Override
    public Boolean action(LocalSession session, ProtoMsg.Message proto) {
        ProtoMsg.MessageRequest messageRequest = proto.getMessageRequest();
        log.info("chatMsg | from="
                + messageRequest.getFrom()
                + " , to =" + messageRequest.getTo()
                + " , MsgType =" + messageRequest.getMsgType()
                + " , content =" + messageRequest.getContent());
        // 获取接收人的chatId
        String to = messageRequest.getTo();
        List<ServerSession> toSessions = SessionManger.inst().getSessionsBy(to);
        if(toSessions == null){
            //接收方离线
            log.info("[" + to + "] 不在线，需要保存为离线消息，请保存到nosql如mongo中!");
        } else {
            // 发送消息给接收方
            toSessions.forEach(serverSession -> {
                serverSession.writeAndFlush(proto);
            });
        }
        long seqNo = proto.getSequence();
        /**
         * 通知客户端：消息发送成功
         */
        ProtoInstant.ResultCodeEnum resultcode = ProtoInstant.ResultCodeEnum.SUCCESS;
        ProtoMsg.Message response =
                ReceiveMessageResponseBuilder.buildChatResponse(resultcode,seqNo);
        session.writeAndFlush(response);
        return true;
    }

    /**
     * 接收tcp消息
     * @param ctx
     * @param proto
     * @return
     */
    @Override
    public Boolean actionTcp(ChannelHandlerContext ctx,ProtoMsg.Message proto){
        ProtoMsg.MessageRequest messageRequest = proto.getMessageRequest();
        log.info("chatMsg | from="
                + messageRequest.getFrom()
                + " , to =" + messageRequest.getTo()
                + " , MsgType =" + messageRequest.getMsgType()
                + " , content =" + messageRequest.getContent());
        // 获取接收人的chatId
        String to = messageRequest.getTo();
        List<ServerSession> toSessions = SessionManger.inst().getSessionsBy(to);
        if(toSessions == null){
            //接收方离线
            log.info("[" + to + "] 不在线，需要保存为离线消息，请保存到nosql如mongo中!");
        } else {
            // 发送消息给接收方
            toSessions.forEach(serverSession -> {
                serverSession.writeAndFlush(proto);
            });
        }
        long seqNo = proto.getSequence();
        /**
         * 通知客户端：消息发送成功
         */
        ProtoInstant.ResultCodeEnum resultcode = ProtoInstant.ResultCodeEnum.SUCCESS;
        ProtoMsg.Message response =
                ReceiveMessageResponseBuilder.buildChatResponse(resultcode,seqNo);
        ctx.writeAndFlush(response);
        return true;
    }
}
